<template>
  <div v-if="!login_state">
    <el-button class="login-btn" type="primary" @click="dialog = true">登录</el-button>
  </div>
  <div v-else style="display: flex; width: 200px; justify-content: space-between;">
    <el-avatar shape="square" size="medium" :src="avatar"/>
    <el-link href="#" style="line-height: 36px; font-size: medium">luoming</el-link>
    <el-button type="info" @click="logout">退出</el-button>
  </div>
  <el-dialog v-model="dialog" title="登录" width="500px">
    <el-form :model="formData" label-position="left" label-width="80px" style="margin: 0 auto; width: 80%">
      <el-form-item label="用户名">
        <el-input v-model="formData.username"/>
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="formData.password" type="password"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span>
        <el-button auto-insert-space type="primary" @click="submit(formData)">
          提交
        </el-button>
        <el-button auto-insert-space @click="dialog = false">
          取消
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import {ElMessage} from 'element-plus'

export default {
  name: "m-login",
  data() {
    return {
      login_state: Boolean(window.sessionStorage.getItem('login_state')),
      dialog: false,
      avatar: this.getImageUrl('avatar','png'),
      formData: {
        username: 'luoming',
        password: 'luoming',
      }
    }
  },
  methods: {
    submit(formData) {
      this.dialog = false
      if (this.formData.username === 'luoming' && this.formData.password === 'luoming') {
        ElMessage({
          message: '登录成功(o゜▽゜)o☆',
          type: 'success'
        })
        window.sessionStorage.setItem('login_state', 'true')
        setTimeout(() => {
          window.location = '/'
        }, 500)
      } else {
        ElMessage({
          message: '登陆失败〒▽〒',
          type: 'error'
        })
        this.dialog = true
      }
    },
    logout() {
      window.sessionStorage.clear()
      window.location.reload()
    },
    getImageUrl(name, extension) {
      return new URL(`../static/imgs/${name}.${extension}`, import.meta.url).href
    },
  }
}
</script>

<style scoped>
template {
  display: flex;
}

.login-btn {
  display: block;
  vertical-align: center;
}
</style>